package cHelper

import (
	"crypto/aes"
	"crypto/cipher"
	"crypto/md5"
	"crypto/sha1"
	"encoding/base64"
	"encoding/hex"
	"fmt"

	"golang.org/x/crypto/bcrypt"
)

func Md5(data []byte) string {
	return fmt.Sprintf("%x", md5.Sum(data))
}

func SHA1(data string) string {
	s := sha1.New()
	s.Write([]byte(data))
	return hex.EncodeToString(s.Sum(nil))
}

func PasswordHash(password string) (hash string, err error) {
	hashBytes, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
	hash = string(hashBytes)
	return
}

func PasswordVerify(password, hash string) bool {
	err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
	return err == nil
}

func AESEncrypt(data, key string) (result string, err error) {
	keyMD5 := Md5([]byte(key))
	keyMD5Bytes := []byte(keyMD5)

	iv := keyMD5Bytes[:aes.BlockSize]
	en := make([]byte, len(data))

	block, err := aes.NewCipher(keyMD5Bytes)
	if err != nil {
		return
	}

	s := cipher.NewCFBEncrypter(block, iv)
	s.XORKeyStream(en, []byte(data))

	result = base64.StdEncoding.EncodeToString(en)

	return
}

func AESDecrypt(data, key string) (result string, err error) {
	keyMD5 := Md5([]byte(key))
	keyMD5Bytes := []byte(keyMD5)

	iv := keyMD5Bytes[:aes.BlockSize]
	en, err := base64.StdEncoding.DecodeString(data)
	if err != nil {
		return
	}

	block, err := aes.NewCipher([]byte(keyMD5))
	if err != nil {
		return
	}

	s := cipher.NewCFBDecrypter(block, iv)
	s.XORKeyStream(en, en)

	result = string(en)

	return
}
